package com.sch.www.codeGenerator.dao;

import freemarker.template.Template;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MybatisGenerator {


    GeneratorProperties gp;

    public MybatisGenerator(GeneratorProperties gp) throws Exception {
        this.gp = gp;
    }

    public void generator() throws Exception {

        List<String> warnings = new ArrayList<>();
        //解析
        ConfigurationParser cp = new ConfigurationParser(warnings);
        File file = File.createTempFile("generator", ".xml");
        createTemplateFile(this.gp, "generatorConfig.ftl", file);
        Configuration config = cp.parseConfiguration(file);
        DefaultShellCallback dsc = new DefaultShellCallback(true);
        MyBatisGenerator mg = new MyBatisGenerator(config, dsc, warnings);
        mg.generate(null);

    }


    private void createTemplateFile(Object data, String templateName, File newFile) throws Exception {
        //设置配置类
        freemarker.template.Configuration configuration = new freemarker.template.Configuration();
        //设置模板所在的目录
        configuration.setClassForTemplateLoading(this.getClass(), "ftl");
        //设置字符集
        configuration.setDefaultEncoding("utf-8");
        //加载模板
        Template template = configuration.getTemplate(templateName);
        //创建Writer对象
        FileWriter writer = new FileWriter(newFile);
        //输出数据模型到文件中
        template.process(data, writer);
        //关闭Writer对象
        writer.flush();
        writer.close();
    }

}
